package com.zhengjiang.generic;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author zhengjiang
 * @version 1.0.0
 * @description 泛型方法
 * @date 2021/6/2
 **/
public class GenericMethodTest {

    static <T> void fromArrayToCollection(T[] a, Collection<T> c){
        for (T t : a){
            c.add(t);
        }
    }

    // 当方法中的形参类型相同时，调用该方法时传入的实参泛型类型必须相同，
    // 否则编译器无法准确的推断方法中泛型形参的类型
    static <T> void copy1(Collection<T> from,Collection<T> to){
        for (T t : from){
            to.add(t);
        }
    }

    //声明一个泛型方法,形参采用类型通配符
    static <T> void copy2(Collection<? extends T> from,Collection<T> to){
        for (T t : from){
            to.add(t);
        }
    }


    public static void main(String[] args) {
        Object[] ob = new Object[100];
        Collection<Object> co = new ArrayList<>();
        fromArrayToCollection(ob,co);

        String[] sa = new String[100];
        Collection<String> cs = new ArrayList<>();
        fromArrayToCollection(sa,cs);


        Integer[] ia = new Integer[100];
        Float[] fa = new Float[100];
        Number[] na = new Number[100];
        Collection<Number> cn = new ArrayList<>();
        fromArrayToCollection(ia,cn);
        fromArrayToCollection(fa,cn);
        fromArrayToCollection(na,cn);

        Collection<Number> nn = new ArrayList<>();
        copy1(cn,nn);
//        copy1(nn,co); //编译器报错
        copy2(nn,co);
    }
}
